#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通用服务器状态监控系统
支持系统资源监控、邮件告警、定时报告等功能
"""

import psutil
import time
import schedule
import threading
import json
import os
import argparse
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import Dict, List, Optional, Callable
import logging
from .email_notifier import EmailNotifier
from .config_manager import ConfigManager
from .utils import format_bytes, safe_print
from .host_monitor import HostMonitor
from .windows_host_monitor import WindowsHostMonitor
from .web_server import MonitorWebServer

# 配置日志
logger = logging.getLogger(__name__)

@dataclass
class MonitorThresholds:
    """监控阈值配置"""
    cpu_warning: float = 70.0      # CPU警告阈值(%)
    cpu_critical: float = 85.0     # CPU严重阈值(%)
    memory_warning: float = 75.0   # 内存警告阈值(%)
    memory_critical: float = 90.0  # 内存严重阈值(%)
    disk_warning: float = 80.0     # 磁盘警告阈值(%)
    disk_critical: float = 95.0    # 磁盘严重阈值(%)
    
    def to_dict(self):
        return {
            'cpu_warning': self.cpu_warning,
            'cpu_critical': self.cpu_critical,
            'memory_warning': self.memory_warning,
            'memory_critical': self.memory_critical,
            'disk_warning': self.disk_warning,
            'disk_critical': self.disk_critical
        }

class ServerMonitor:
    """通用服务器监控器"""
    
    def __init__(self, config_manager: ConfigManager, email_notifier: EmailNotifier = None):
        """
        初始化服务器监控器
        
        Args:
            config_manager: 配置管理器
            email_notifier: 邮件通知器（可选）
        """
        self.config = config_manager
        self.email_notifier = email_notifier
        self.thresholds = MonitorThresholds(**config_manager.get('thresholds', {}))
        
        self.last_alert_time = {}  # 记录上次告警时间，避免频繁发送
        self.alert_cooldown = config_manager.get('alert_settings.cooldown_minutes', 5) * 60  # 告警冷却时间(秒)
        self.monitoring = False
        self.monitor_thread = None
        
        # 自定义检查器列表
        self.custom_checkers = []
        
        # 初始化主机监控器
        self.host_monitor = HostMonitor()
        self.windows_host_monitor = WindowsHostMonitor()
        
        # 选择合适的监控器
        if self.windows_host_monitor.is_windows_host:
            logger.info("使用Windows主机监控器")
            self.active_monitor = self.windows_host_monitor
        else:
            logger.info("使用Linux主机监控器")
            self.active_monitor = self.host_monitor
        
        # 初始化Web服务器
        self.web_server = None
        web_config = config_manager.get('web', {})
        if web_config.get('enabled', False):
            web_host = web_config.get('host', '0.0.0.0')
            web_port = web_config.get('port', 8080)
            self.web_server = MonitorWebServer(self, web_host, web_port)
            logger.info(f"Web服务器已配置: {web_host}:{web_port}")
        
        # 确保日志目录存在
        os.makedirs('logs', exist_ok=True)
        
    def add_custom_checker(self, checker_func: Callable[[], List[Dict]]):
        """
        添加自定义检查器
        
        Args:
            checker_func: 检查函数，返回告警列表
        """
        self.custom_checkers.append(checker_func)
        
    def get_system_status(self) -> Dict:
        """获取系统状态信息"""
        try:
            # 使用选定的监控器获取系统状态
            if hasattr(self.active_monitor, 'get_comprehensive_status'):
                return self.active_monitor.get_comprehensive_status()
            else:
                # 回退到原有的主机监控逻辑
                return self.host_monitor.get_comprehensive_status()
            
        except Exception as e:
            logger.error(f"获取系统状态失败: {e}")
            # 回退到原始的psutil方法
            return self._get_fallback_system_status()
    
    def _get_fallback_system_status(self) -> Dict:
        """回退的系统状态获取方法"""
        try:
            # CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            cpu_count = psutil.cpu_count()
            cpu_freq = psutil.cpu_freq()
            
            # 内存信息
            memory = psutil.virtual_memory()
            
            # 磁盘信息
            disk_usage = {}
            for partition in psutil.disk_partitions():
                try:
                    partition_usage = psutil.disk_usage(partition.mountpoint)
                    disk_usage[partition.mountpoint] = {
                        'total': partition_usage.total,
                        'used': partition_usage.used,
                        'free': partition_usage.free,
                        'percent': (partition_usage.used / partition_usage.total) * 100
                    }
                except PermissionError:
                    continue
            
            # 网络信息
            network = psutil.net_io_counters()
            
            # 系统负载
            try:
                load_avg = os.getloadavg()
            except (OSError, AttributeError):
                load_avg = [0, 0, 0]  # Windows系统不支持
            
            # 进程信息
            processes = []
            for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
                try:
                    processes.append(proc.info)
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue
            
            # 按CPU使用率排序，取前5个
            processes.sort(key=lambda x: x.get('cpu_percent', 0), reverse=True)
            top_processes = processes[:5]
            
            # 系统启动时间
            boot_time = datetime.fromtimestamp(psutil.boot_time())
            uptime = datetime.now() - boot_time
            
            return {
                'timestamp': datetime.now().isoformat(),
                'cpu': {
                    'percent': cpu_percent,
                    'count': cpu_count,
                    'frequency': cpu_freq.current if cpu_freq else 0,
                    'load_avg': load_avg
                },
                'memory': {
                    'total': memory.total,
                    'available': memory.available,
                    'used': memory.used,
                    'free': memory.free,
                    'percent': memory.percent,
                    'buffers': getattr(memory, 'buffers', 0),
                    'cached': getattr(memory, 'cached', 0)
                },
                'disk': disk_usage,
                'network': {
                    'bytes_sent': network.bytes_sent,
                    'bytes_recv': network.bytes_recv,
                    'packets_sent': network.packets_sent,
                    'packets_recv': network.packets_recv
                },
                'processes': top_processes,
                'uptime': str(uptime).split('.')[0],
                'boot_time': boot_time.isoformat(),
                'monitoring_info': {
                    'is_container': False,
                    'monitoring_mode': '回退模式'
                }
            }
        except Exception as e:
            logger.error(f"回退方法也失败: {e}")
            return {}
    
    def check_thresholds(self, status: Dict) -> List[Dict]:
        """检查阈值，返回告警信息"""
        alerts = []
        
        # 检查CPU
        cpu_percent = status.get('cpu', {}).get('percent', 0)
        if cpu_percent >= self.thresholds.cpu_critical:
            alerts.append({
                'type': 'cpu',
                'level': 'critical',
                'message': f'CPU使用率严重过高: {cpu_percent:.1f}%',
                'value': cpu_percent,
                'threshold': self.thresholds.cpu_critical
            })
        elif cpu_percent >= self.thresholds.cpu_warning:
            alerts.append({
                'type': 'cpu',
                'level': 'warning',
                'message': f'CPU使用率过高: {cpu_percent:.1f}%',
                'value': cpu_percent,
                'threshold': self.thresholds.cpu_warning
            })
        
        # 检查内存
        memory_percent = status.get('memory', {}).get('percent', 0)
        if memory_percent >= self.thresholds.memory_critical:
            alerts.append({
                'type': 'memory',
                'level': 'critical',
                'message': f'内存使用率严重过高: {memory_percent:.1f}%',
                'value': memory_percent,
                'threshold': self.thresholds.memory_critical
            })
        elif memory_percent >= self.thresholds.memory_warning:
            alerts.append({
                'type': 'memory',
                'level': 'warning',
                'message': f'内存使用率过高: {memory_percent:.1f}%',
                'value': memory_percent,
                'threshold': self.thresholds.memory_warning
            })
        
        # 检查磁盘
        for mountpoint, disk_info in status.get('disk', {}).items():
            disk_percent = disk_info.get('percent', 0)
            if disk_percent >= self.thresholds.disk_critical:
                alerts.append({
                    'type': 'disk',
                    'level': 'critical',
                    'message': f'磁盘使用率严重过高 ({mountpoint}): {disk_percent:.1f}%',
                    'value': disk_percent,
                    'threshold': self.thresholds.disk_critical,
                    'mountpoint': mountpoint
                })
            elif disk_percent >= self.thresholds.disk_warning:
                alerts.append({
                    'type': 'disk',
                    'level': 'warning',
                    'message': f'磁盘使用率过高 ({mountpoint}): {disk_percent:.1f}%',
                    'value': disk_percent,
                    'threshold': self.thresholds.disk_warning,
                    'mountpoint': mountpoint
                })
        
        # 执行自定义检查器
        for checker in self.custom_checkers:
            try:
                custom_alerts = checker()
                if custom_alerts:
                    alerts.extend(custom_alerts)
            except Exception as e:
                logger.error(f"自定义检查器执行失败: {e}")
                alerts.append({
                    'type': 'custom_checker',
                    'level': 'critical',
                    'message': f'自定义检查器执行失败: {str(e)}',
                    'value': 0,
                    'threshold': 0
                })
        
        return alerts
    
    def should_send_alert(self, alert_type: str) -> bool:
        """检查是否应该发送告警（避免频繁发送）"""
        now = time.time()
        last_time = self.last_alert_time.get(alert_type, 0)
        
        if now - last_time >= self.alert_cooldown:
            self.last_alert_time[alert_type] = now
            return True
        return False
    
    def generate_html_report(self, status: Dict, alerts: List[Dict] = None) -> str:
        """生成HTML格式的报告"""
        if alerts is None:
            alerts = []
        
        # 获取磁盘总使用率（取最高的）
        max_disk_percent = 0
        max_disk_mount = "/"
        for mountpoint, disk_info in status.get('disk', {}).items():
            if disk_info.get('percent', 0) > max_disk_percent:
                max_disk_percent = disk_info.get('percent', 0)
                max_disk_mount = mountpoint
        
        # 确定整体状态
        overall_status = "正常"
        status_color = "#28a745"  # 绿色
        
        if alerts:
            critical_alerts = [a for a in alerts if a['level'] == 'critical']
            if critical_alerts:
                overall_status = "严重"
                status_color = "#dc3545"  # 红色
            else:
                overall_status = "警告"
                status_color = "#ffc107"  # 黄色
        
        server_name = self.config.get('server_name', '服务器')
        
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>{server_name}监控报告</title>
            <style>
                body {{ font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 10px; background-color: #f8f9fa; }}
                .container {{ max-width: 100%; margin: 0 auto; background-color: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
                .header {{ text-align: center; margin-bottom: 20px; padding: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px; }}
                .status-card {{ display: flex; flex-wrap: wrap; justify-content: space-around; margin-bottom: 20px; gap: 10px; }}
                .card {{ background: white; padding: 12px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); text-align: center; flex: 1; min-width: 120px; max-width: 180px; }}
                .card h3 {{ margin: 0 0 8px 0; color: #333; font-size: 14px; }}
                .card .value {{ font-size: 20px; font-weight: bold; margin: 5px 0; }}
                .card small {{ font-size: 11px; color: #666; word-break: break-all; display: block; margin-top: 5px; }}
                .normal {{ color: #28a745; }}
                .warning {{ color: #ffc107; }}
                .critical {{ color: #dc3545; }}
                .alert {{ padding: 10px; margin: 10px 0; border-radius: 5px; border-left: 4px solid; }}
                .alert-warning {{ background-color: #fff3cd; border-color: #ffc107; color: #856404; }}
                .alert-critical {{ background-color: #f8d7da; border-color: #dc3545; color: #721c24; }}
                .info-table {{ width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 13px; }}
                .info-table th, .info-table td {{ padding: 6px 8px; text-align: left; border-bottom: 1px solid #ddd; word-break: break-word; }}
                .info-table th {{ background-color: #f8f9fa; font-weight: bold; }}
                .progress-bar {{ background-color: #e9ecef; height: 16px; border-radius: 8px; overflow: hidden; margin: 5px 0; }}
                .progress-fill {{ height: 100%; transition: width 0.3s ease; }}
                .footer {{ text-align: center; margin-top: 30px; color: #6c757d; font-size: 11px; }}
                /* 移动端适配 */
                @media screen and (max-width: 600px) {{
                    body {{ margin: 5px; }}
                    .container {{ padding: 10px; }}
                    .header {{ padding: 10px; }}
                    .status-card {{ flex-direction: column; align-items: center; }}
                    .card {{ max-width: 100%; margin-bottom: 10px; }}
                    .card h3 {{ font-size: 13px; }}
                    .card .value {{ font-size: 18px; }}
                    .info-table {{ font-size: 12px; }}
                    .info-table th, .info-table td {{ padding: 4px 6px; }}
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>🖥️ {server_name}监控报告</h1>
                    <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
                    <p>系统状态: <span style="color: {status_color}; font-weight: bold;">{overall_status}</span></p>
                </div>
        """
        
        # 告警信息
        if alerts:
            html += "<div style='margin-bottom: 20px;'>"
            html += "<h2 style='color: #dc3545;'>🚨 告警信息</h2>"
            for alert in alerts:
                alert_class = f"alert-{alert['level']}"
                html += f"<div class='alert {alert_class}'>"
                html += f"<strong>{alert['level'].upper()}:</strong> {alert['message']}"
                html += "</div>"
            html += "</div>"
        
        # 系统状态卡片
        cpu_percent = status.get('cpu', {}).get('percent', 0)
        memory_percent = status.get('memory', {}).get('percent', 0)
        memory_used = format_bytes(status.get('memory', {}).get('used', 0))
        memory_total = format_bytes(status.get('memory', {}).get('total', 0))
        
        # 确定状态颜色
        cpu_class = 'critical' if cpu_percent >= self.thresholds.cpu_critical else ('warning' if cpu_percent >= self.thresholds.cpu_warning else 'normal')
        memory_class = 'critical' if memory_percent >= self.thresholds.memory_critical else ('warning' if memory_percent >= self.thresholds.memory_warning else 'normal')
        disk_class = 'critical' if max_disk_percent >= self.thresholds.disk_critical else ('warning' if max_disk_percent >= self.thresholds.disk_warning else 'normal')
        
        html += f"""
                <div class="status-card">
                    <div class="card">
                        <h3>CPU使用率</h3>
                        <div class="value {cpu_class}">{cpu_percent:.1f}%</div>
                        <small>核心数: {status.get('cpu', {}).get('count', 0)}</small>
                    </div>
                    <div class="card">
                        <h3>内存使用率</h3>
                        <div class="value {memory_class}">{memory_percent:.1f}%</div>
                        <small>{memory_used} / {memory_total}</small>
                    </div>
                    <div class="card">
                        <h3>磁盘使用率</h3>
                        <div class="value {disk_class}">{max_disk_percent:.1f}%</div>
                        <small>{max_disk_mount}</small>
                    </div>
                    <div class="card">
                        <h3>系统运行时间</h3>
                        <div class="value normal">{status.get('uptime', 'N/A')}</div>
                        <small>启动时间: {datetime.fromisoformat(status.get('boot_time', '')).strftime('%m-%d %H:%M') if status.get('boot_time') else 'N/A'}</small>
                    </div>
                </div>
        """
        
        # 详细信息表格
        html += """
                <h2>📊 详细信息</h2>
                <table class="info-table">
                    <tr><th>项目</th><th>当前值</th><th>详细信息</th></tr>
        """
        
        # CPU信息
        html += f"""
                    <tr>
                        <td>CPU</td>
                        <td>{cpu_percent:.1f}%</td>
                        <td>核心数: {status.get('cpu', {}).get('count', 0)}, 频率: {status.get('cpu', {}).get('frequency', 0):.0f}MHz</td>
                    </tr>
        """
        
        # 内存信息
        html += f"""
                    <tr>
                        <td>内存</td>
                        <td>{memory_percent:.1f}%</td>
                        <td>已用: {memory_used}, 总计: {memory_total}, 可用: {format_bytes(status.get('memory', {}).get('available', 0))}</td>
                    </tr>
        """
        
        # 磁盘信息
        for mountpoint, disk_info in status.get('disk', {}).items():
            disk_percent = disk_info.get('percent', 0)
            disk_used = format_bytes(disk_info.get('used', 0))
            disk_total = format_bytes(disk_info.get('total', 0))
            html += f"""
                    <tr>
                        <td>磁盘 ({mountpoint})</td>
                        <td>{disk_percent:.1f}%</td>
                        <td>已用: {disk_used}, 总计: {disk_total}</td>
                    </tr>
            """
        
        # 网络信息
        network_sent = format_bytes(status.get('network', {}).get('bytes_sent', 0))
        network_recv = format_bytes(status.get('network', {}).get('bytes_recv', 0))
        html += f"""
                    <tr>
                        <td>网络</td>
                        <td>发送: {network_sent}</td>
                        <td>接收: {network_recv}</td>
                    </tr>
        """
        
        html += "</table>"
        
        # 进程信息
        if status.get('top_processes'):
            html += """
                <h2>🔝 CPU占用最高的进程</h2>
                <table class="info-table">
                    <tr><th>PID</th><th>进程名</th><th>CPU%</th><th>内存%</th></tr>
            """
            for proc in status.get('top_processes', []):
                html += f"""
                    <tr>
                        <td>{proc.get('pid', 'N/A')}</td>
                        <td>{proc.get('name', 'N/A')}</td>
                        <td>{proc.get('cpu_percent', 0):.1f}%</td>
                        <td>{proc.get('memory_percent', 0):.1f}%</td>
                    </tr>
                """
            html += "</table>"
        
        html += """
                <div class="footer">
                    <p>通用服务器监控系统 - 自动生成报告</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return html
    
    def send_alert_email(self, alerts: List[Dict], status: Dict):
        """发送告警邮件"""
        if not self.email_notifier:
            logger.warning("邮件通知器未配置，跳过告警邮件发送")
            return
        
        # 检查是否需要发送告警
        alert_types = [alert['type'] for alert in alerts]
        should_send = any(self.should_send_alert(alert_type) for alert_type in alert_types)
        
        if not should_send:
            logger.info("告警冷却期内，跳过邮件发送")
            return
        
        # 生成邮件内容
        critical_count = len([a for a in alerts if a['level'] == 'critical'])
        warning_count = len([a for a in alerts if a['level'] == 'warning'])
        
        if critical_count > 0:
            subject = f"🚨 {self.config.get('server_name', '服务器')}严重告警 - {critical_count}个严重问题"
        else:
            subject = f"⚠️ {self.config.get('server_name', '服务器')}监控告警 - {warning_count}个警告"
        
        html_content = self.generate_html_report(status, alerts)
        
        try:
            self.email_notifier.send_email(subject, html_content, is_html=True)
            logger.info(f"告警邮件发送成功: {subject}")
        except Exception as e:
            logger.error(f"告警邮件发送失败: {e}")
    
    def send_daily_report(self):
        """发送日常报告"""
        if not self.email_notifier:
            logger.warning("邮件通知器未配置，跳过日常报告发送")
            return
        
        try:
            status = self.get_system_status()
            alerts = self.check_thresholds(status)
            
            subject = f"📊 {self.config.get('server_name', '服务器')}日常监控报告 - {datetime.now().strftime('%Y-%m-%d')}"
            html_content = self.generate_html_report(status, alerts)
            
            self.email_notifier.send_email(subject, html_content, is_html=True)
            logger.info("日常报告发送成功")
        except Exception as e:
            logger.error(f"日常报告发送失败: {e}")
    
    def monitor_loop(self):
        """监控循环"""
        logger.info("开始监控循环")
        
        while self.monitoring:
            try:
                # 获取系统状态
                status = self.get_system_status()
                if not status:
                    logger.warning("无法获取系统状态，跳过本次检查")
                    time.sleep(60)
                    continue
                
                # 检查阈值
                alerts = self.check_thresholds(status)
                
                # 记录状态
                cpu_percent = status.get('cpu', {}).get('percent', 0)
                memory_percent = status.get('memory', {}).get('percent', 0)
                logger.info(f"系统状态 - CPU: {cpu_percent:.1f}%, 内存: {memory_percent:.1f}%")
                
                # 发送告警邮件
                if alerts:
                    logger.warning(f"检测到 {len(alerts)} 个告警")
                    self.send_alert_email(alerts, status)
                
                # 等待下次检查
                check_interval = self.config.get('monitoring.check_interval_seconds', 60)
                time.sleep(check_interval)
                
            except Exception as e:
                logger.error(f"监控循环出错: {e}")
                time.sleep(60)
    
    def start_monitoring(self):
        """开始监控"""
        if self.monitoring:
            logger.warning("监控已在运行中")
            return
        
        self.monitoring = True
        
        # 启动Web服务器
        if self.web_server:
            self.web_server.start()
        
        # 设置定时任务
        daily_report_time = self.config.get('schedule.daily_report_time', '09:00')
        schedule.every().day.at(daily_report_time).do(self.send_daily_report)
        
        weekly_report_day = self.config.get('schedule.weekly_report_day', 'monday')
        weekly_report_time = self.config.get('schedule.weekly_report_time', '09:30')
        getattr(schedule.every(), weekly_report_day).at(weekly_report_time).do(self.send_daily_report)
        
        # 启动监控线程
        self.monitor_thread = threading.Thread(target=self.monitor_loop, daemon=True)
        self.monitor_thread.start()
        
        # 启动定时任务线程
        def schedule_loop():
            while self.monitoring:
                schedule.run_pending()
                time.sleep(60)
        
        schedule_thread = threading.Thread(target=schedule_loop, daemon=True)
        schedule_thread.start()
        
        logger.info("服务器监控已启动")
    
    def stop_monitoring(self):
        """停止监控"""
        self.monitoring = False
        
        # 停止Web服务器
        if self.web_server:
            self.web_server.stop()
        
        schedule.clear()
        logger.info("服务器监控已停止")
    
    def test_email(self):
        """测试邮件发送"""
        if not self.email_notifier:
            safe_print("❌ 邮件通知器未配置")
            return False
        
        try:
            status = self.get_system_status()
            subject = f"📧 {self.config.get('server_name', '服务器')}监控系统测试邮件"
            content = self.generate_html_report(status)
            
            self.email_notifier.send_email(subject, content, is_html=True)
            safe_print("✅ 测试邮件发送成功")
            return True
        except Exception as e:
            safe_print(f"❌ 测试邮件发送失败: {e}")
            return False


def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description='通用服务器监控系统')
    parser.add_argument('--config', '-c', type=str, help='配置文件路径')
    parser.add_argument('--interval', '-i', type=int, default=300, help='检查间隔（秒）')
    parser.add_argument('--once', action='store_true', help='只检查一次，不持续监控')
    parser.add_argument('--test-email', action='store_true', help='测试邮件发送')
    parser.add_argument('--daemon', '-d', action='store_true', help='后台运行')
    parser.add_argument('--verbose', '-v', action='store_true', help='详细输出')
    
    return parser.parse_args()


def main():
    """主函数"""
    args = parse_arguments()
    
    # 设置日志级别
    log_level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(
        level=log_level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('logs/server_monitor.log'),
            logging.StreamHandler()
        ]
    )
    
    try:
        # 初始化配置管理器
        config_manager = ConfigManager(config_file=args.config)
        
        # 初始化邮件通知器
        email_notifier = None
        if config_manager.is_email_enabled():
            email_config = config_manager.get_email_config()
            email_notifier = EmailNotifier(email_config)
        
        # 创建监控器
        monitor = ServerMonitor(config_manager, email_notifier)
        
        if args.test_email:
            # 测试邮件发送
            safe_print("🧪 测试邮件发送...")
            monitor.test_email()
            return
        
        if args.once:
            # 只检查一次
            safe_print("🔍 检查当前系统状态...")
            status = monitor.get_system_status()
            alerts = monitor.check_thresholds(status)
            
            # 显示状态
            cpu_percent = status.get('cpu', {}).get('percent', 0)
            memory_percent = status.get('memory', {}).get('percent', 0)
            safe_print(f"CPU: {cpu_percent:.1f}%")
            safe_print(f"内存: {memory_percent:.1f}%")
            
            if alerts:
                safe_print(f"⚠️  检测到 {len(alerts)} 个告警:")
                for alert in alerts:
                    emoji = "🔴" if alert['level'] == 'critical' else "🟡"
                    safe_print(f"  {emoji} {alert['message']}")
            else:
                safe_print("✅ 系统状态正常")
        else:
            # 持续监控
            safe_print("🚀 启动服务器监控...")
            safe_print(f"检查间隔: {args.interval}秒")
            if email_notifier:
                safe_print("📧 邮件通知已启用")
            else:
                safe_print("📧 邮件通知未启用")
            
            # 更新检查间隔
            config_manager._config.setdefault('monitoring', {})['check_interval_seconds'] = args.interval
            
            monitor.start_monitoring()
            
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                safe_print("\n🛑 收到停止信号，正在关闭监控...")
                monitor.stop_monitoring()
                safe_print("✅ 监控已停止")
    
    except Exception as e:
        logger.error(f"程序运行出错: {e}")
        safe_print(f"❌ 程序运行出错: {e}")
        return 1
    
    return 0


if __name__ == "__main__":
    exit(main())